/**
 * 
 */
package com.maywide.jdp.system.aspect;

import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.jboss.cache.Cache;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.maywide.jdp.core.exception.AppException;
import com.maywide.jdp.system.bean.ModuleBean;
import com.maywide.jdp.system.entities.Module;

/**
 * @author luoyang
 */
@Aspect
@Component("moduleAspect")
public class ModuleAspect {
	private Cache<String, Object> cache = null;
	private ModuleBean bean = null;
	
	@Resource(name = "cache")
	public void setCache(Cache<String, Object> cache) {
		this.cache = cache;
	}

	@Resource(name = "moduleBean")
	public void setBean(ModuleBean bean) {
		this.bean = bean;
	}

	@SuppressWarnings({ "unused" })
	@Order(100)
	@AfterReturning(pointcut="execution(public * com.maywide.jdp.system.service.ModuleService.update*(..)) and args(moduleVO,..,request,response,session)",returning="retVal",argNames="retVal,moduleVO,request,response,session")
	private void doUpdate(Object retVal,Module moduleVO,HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		if(moduleVO.getType().equals(Module.TYPE_BEAN)) {
			String beanName = moduleVO.getBeanName();
			if(beanName == null)
				throw new AppException("组件类型模块的组件名不能为空!");
			ServletContext servletContext = session.getServletContext();
			WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
			if(!context.containsBean(beanName))
				throw new AppException("组件类型模块的组件名对应的组件不存在!");
		}
		
		Module old = (Module) bean.load(moduleVO.getId());
		
		String oldPath = new StringBuffer("/rules/").append(old.getBeanName()).toString();
		String newPath = new StringBuffer("/rules/").append(moduleVO.getBeanName()).toString();
		
		if(!oldPath.equals(newPath)) {
			Node<String, Object> tareget = cache.getRoot().addChild(Fqn.fromString(newPath));
			Set<Node<String, Object>> children = cache.getNode(Fqn.fromString(oldPath)).getChildren();
			if(children != null) {
				for(Node<String, Object> child : children) {
					cache.move(child.getFqn(), tareget.getFqn());
				}
			}
		}
	}
}
